#include "common.h"

int make_nonblock(int fd) {
    int flag;
    if ((flag = fcntl(fd, F_GETFL)) < 0)
        return -1;
    flag |= O_NONBLOCK;
    if (fcntl(fd, F_SETFL, flag) < 0)
        return -1;
    return 0;
}

int make_block(int fd) {
    int flag;
    if ((flag = fcntl(fd, F_GETFL)) < 0)
        return -1;
    flag &= ~O_NONBLOCK;
    if (fcntl(fd, F_SETFL, flag) < 0)
        return -1;
    return 0;
}

int socket_create(int port) {
    int sockfd;
    struct sockaddr_in addr;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
        return -1;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    // close socker 后想继续重用该 socket
    int reuse = -1;
    setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (char *)&reuse, sizeof(int));

    if (bind(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) < 0)
        return -1;
    // 主动套接字转被动监听
    // backlog: 记录队列中正在连接还未连接上的客户
    if (listen(sockfd, 20) < 0)
        return -1;
    return sockfd;
}

int socket_connect(const char *ip, int port) {
    int sockfd;
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
            return -1;

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip); // 将字符串形式的IP地址转换为32位网络字节序二进制IP地址的函数

    if (connect(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
            return -1;
    return sockfd;
}